from stark.service.stark import StarkConfig
from crm_app import models
from django.utils.safestring import mark_safe
from django.conf.urls import url
from django.shortcuts import render, redirect
from django import forms
from django.forms import modelformset_factory
from crm_app.permission.base import BASERbacPermission


class StudyRecordModelForm(forms.ModelForm):
    class Meta:
        model = models.StudyRecord
        fields = ["student", "record", "score", "homework_note"]


class StudyRecordConfig(BASERbacPermission, StarkConfig):
    # def display_name(self, row=None, header=False):
    #     if header:
    #         return "姓名"
    #     return row.student.customer.name
    #
    # list_display = [display_name]
    #
    # def get_queryset(self):
    #     ccid = self.request.GET.get("ccid")
    #     if not ccid:
    #         return models.StudyRecord.objects.none()
    #     return models.StudyRecord.objects.filter(course_record_id=ccid)
    #
    # def get_add_btn(self):
    #     return False
    #
    # def get_list_display(self):
    #     val = super().get_list_display()
    #     val.remove(StarkConfig.display_del)  # 默认公户不显示删除操作
    #     return val

    def get_urls(self):
        urlpatterns = [
            url(r'^list/', self.wrapper(self.changelist_view), name=self.get_list_url_name),
        ]

        return urlpatterns

    def changelist_view(self, request):
        ccid = request.GET.get("ccid")
        model_formset_cls = modelformset_factory(models.StudyRecord, StudyRecordModelForm, extra=0)
        queryset = models.StudyRecord.objects.filter(course_record_id=ccid)
        if request.method == 'GET':
            formset = model_formset_cls(queryset=queryset)
            return render(request, "study_record.html", {"formset": formset})

        formset = model_formset_cls(data=request.POST)
        if formset.is_valid():
            formset.save()
            return redirect("/stark/crm_app/studyrecord/list/?ccid=%s" % ccid)

        return render(request, "study_record.html", {"formset": formset})
